import React, {useState, useEffect} from 'react'

import { List, Avatar, Space, Tag, message, Empty, Skeleton, Modal, Tooltip } from 'antd'

import MyCard from '../../../components/MyCard'

import defaultSettings from '../../../defaultSettings'

import countFormat from '../../../assets/js/countFormat'

import { LikeOutlined, StarOutlined, StarTwoTone, LikeTwoTone, SyncOutlined, SoundOutlined, RedEnvelopeTwoTone } from '@ant-design/icons'

import { Container } from './style'

import {connect} from 'react-redux'
import {changeHomeArticleList, changeHomeTopDis} from '../../../store/actionCreators'

import moment from 'moment'
import 'moment/locale/zh-cn'

import { PhotoProvider, PhotoConsumer } from 'react-photo-view'
import 'react-photo-view/dist/index.css'

import ArticleRequest from '../../../request/article_request'

const article_request = new ArticleRequest()

function Home(props) {
    const {history, keyword, homeArticleList, changeHomeArticleList, homeTopDis, changeHomeTopDis} = props

    const [aWordObj, setAWordObj] = useState({})

    const [articleList, setArticleList] = useState([{}, {}, {}, {}, {}])

    const [guessList, setGuessList] = useState([])

    const [rankList, setRankList] = useState([])

    const [changeGuessLoading, setChangeGuessLoading] = useState(false)

    const [showSkeleton, setShowSkeleton] = useState(false)

    const [appreciateVisible, setAppreciateVisible] = useState(false)

    const getRandomWord = () => {
        article_request.getRandomWord().then(res => {
            setAWordObj(res)
        })
    }

    const getArticleList = () => {
        article_request.getArticleList({
            title: keyword,
            type: '2'
        }).then(res => {
            let topList = []
            let otherList = []
            res.forEach(item => {
                if(item.istop === '1'){
                    topList.push(item)
                }else{
                    otherList.push(item)
                }
            })
            topList = topList.sort((a, b) => {
                return Number(b.topDate) - Number(a.topDate)
            })
            setArticleList([...topList, ...otherList])
            changeHomeArticleList([...topList, ...otherList])
            setShowSkeleton(false)
        })
    }

    const collectArticle = (id, title, desc) => {
        article_request.collectArticle({
            id,
            title,
            desc
        }).then(res => {
            if(window.isMobile){
                message.success('已收藏，请在PC端查看')
            }else{
                message.success('已加入收藏')
            }
            getArticleList()
        })
    }

    const likeArticle = (id) => {
        article_request.likeArticle({
            id
        }).then(res => {
            getArticleList()
        })
    }

    const getRankList = () => {
        article_request.getRankList().then(res => {
            setRankList(res)
        })
    }

    const getGuessList = () => {
        setChangeGuessLoading(true)
        article_request.getGuessList().then(res => {
            setGuessList(res)
            setChangeGuessLoading(false)
        })
    }

    const appreciateArticle = () => {
        setAppreciateVisible(true)
    }

    // 监听首页滚动事件，记住滚动位置
    const getScrollPosition = () => {
        document.getElementById('article-top-c').onscroll = (e) => {
            if(history.location.pathname === '/article/home'){
                changeHomeTopDis(e.target.scrollTop)
            }
        }
    }

    useEffect(() => {
        if(homeArticleList.length !== 0){
            setArticleList(homeArticleList)
            setShowSkeleton(false)
            document.getElementById('article-top-c').scrollTop = homeTopDis
        }else{
            setShowSkeleton(true)
        }
    }, [])

    useEffect(() => {
        getRankList()
        getGuessList()
        getRandomWord()
        
        getScrollPosition()
    }, [])

    useEffect(() => {
        getArticleList()
    }, [keyword])
    return (
        <Container>
            <div className="left">
                <MyCard title="小站致辞" style={{marginBottom: 20}}>
                    <div className="desc">
                        {/* <Avatar size={54} shape="square" src={defaultSettings.webUrl} /> */}
                        <div className="welcome">
                            <svg width="170" height="30">
                                <defs>
                                    <linearGradient id="g3" x1="0%" y1="0%" x2="0" y2="100%">
                                        <stop offset="0%" stopColor="#007aff"></stop>
                                        <stop offset="50%" stopColor="#3aa4ff"></stop>
                                        <stop offset="100%" stopColor="#00b7ee"></stop>
                                    </linearGradient>
                                </defs>
                                <text fontSize="20" fontWeight="bold" x="0" y="22" fill="url(#g3)">欢迎进入八翼小站</text>
                            </svg>
                        </div>
                        <div className="desc-item">
                            <svg t="1583933441119" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10007" width="20" height="20" fill="currentColor">
                                <path d="M475.428571 548.571429l0 219.428571q0 45.714286-32.036571 77.677714t-77.677714 32.036571l-219.428571 0q-45.714286 0-77.677714-32.036571t-32.036571-77.677714l0-402.285714q0-59.465143 23.113143-113.444571t62.537143-93.403429 93.403429-62.537143 113.444571-23.113143l36.571429 0q14.848 0 25.746286 10.825143t10.825143 25.746286l0 73.142857q0 14.848-10.825143 25.746286t-25.746286 10.825143l-36.571429 0q-60.562286 0-103.424 42.861714t-42.861714 103.424l0 18.285714q0 22.820571 16.018286 38.838857t38.838857 16.018286l128 0q45.714286 0 77.677714 32.036571t32.036571 77.677714zM987.428571 548.571429l0 219.428571q0 45.714286-32.036571 77.677714t-77.677714 32.036571l-219.428571 0q-45.714286 0-77.677714-32.036571t-32.036571-77.677714l0-402.285714q0-59.465143 23.113143-113.444571t62.537143-93.403429 93.403429-62.537143 113.444571-23.113143l36.571429 0q14.848 0 25.746286 10.825143t10.825143 25.746286l0 73.142857q0 14.848-10.825143 25.746286t-25.746286 10.825143l-36.571429 0q-60.562286 0-103.424 42.861714t-42.861714 103.424l0 18.285714q0 22.820571 16.018286 38.838857t38.838857 16.018286l128 0q45.714286 0 77.677714 32.036571t32.036571 77.677714z" p-id="10008"></path>
                            </svg>
                            <span>{aWordObj.hitokoto || ''}</span>
                            <p>- {aWordObj.from || ''}</p>
                        </div>
                    </div>
                </MyCard>
                <MyCard notTitle={true} style={{marginBottom: 20}}>
                    <div className="link">
                        <PhotoProvider>
                            <PhotoConsumer src={require("../../../assets/img/mobile.png")} intro={'手机扫码访问本站'}>
                                <img src={require("../../../assets/img/mobile.png")} alt=""/>
                            </PhotoConsumer>
                        </PhotoProvider>
                        <div className="link-right">
                            <div className="link-right-title">手机扫描二维码访问本站</div>
                            <div className="link-right-subtitle">一个专注于前端技术的博客</div>
                        </div>
                        {
                            window.isMobile ?
                            <div className="link-money" onClick={appreciateArticle}>
                                <RedEnvelopeTwoTone twoToneColor="#faad14"/>
                            </div> :
                            <Tooltip placement="top" title="支持一下">
                                <div className="link-money" onClick={appreciateArticle}>
                                    <RedEnvelopeTwoTone twoToneColor="#faad14"/>
                                </div>
                            </Tooltip>
                        }
                    </div>
                </MyCard>
                <MyCard title="猜你喜欢" style={{marginBottom: 20}} extra={
                    <div style={{display: 'flex', alignItems: 'center', cursor: 'pointer', userSelect: 'none'}} onClick={() => getGuessList()}><SyncOutlined spin={changeGuessLoading} style={{marginRight: 4}}/><span>换一换</span></div>
                }>
                    <div className="guess">
                        {
                            guessList.length !== 0 ? guessList.map((item, index) => {
                                return (
                                    <div className="guess-item" key={index} onClick={() => history.push('/article/detail/' + item.id)}>
                                        <div className="line"></div>
                                        <div className="title like">{item.title}</div>
                                    </div>
                                )
                            })
                            : <Empty description={false} style={{margin: '24px 0'}}/>
                        }
                    </div>
                </MyCard>
                <MyCard title="热度排行">
                    <div className="guess">
                        {
                            rankList.length !== 0 ? rankList.map((item, index) => {
                                return (
                                    <div className="guess-item" key={index} onClick={() => history.push('/article/detail/' + item.id)}>
                                        <div className="line"></div>
                                        <div className="title"><span className="num">{index + 1}</span><span className="value">{item.title}</span></div>
                                    </div>
                                )
                            })
                            : <Empty description={false} style={{margin: '24px 0'}}/>
                        }
                    </div>
                </MyCard>
            </div>
            <div className="right">
                {/* 博客公告栏 */}
                {/* <div className="article-top-notice">
                    <Tag className="article-top-notice-title" color="orange" icon={<SoundOutlined />}>即将发布：论在当前像是吓唬工作四是无数无数无数数文化苏伟五级的重要性</Tag>
                </div> */}
                <List
                    itemLayout="vertical"
                    size="large"
                    // pagination={{
                    //     onChange: page => {
                    //         console.log(page);
                    //     },
                    //     pageSize: 5,
                    // }}
                    dataSource={articleList}
                    renderItem={(item, index) => (
                        <List.Item
                            className="article-item"
                            key={item.title}
                            actions={[
                                <span key="list-vertical-date">{item.createdate && moment(Number(item.createdate)).fromNow()}</span>,
                                <span key="list-vertical-read">{countFormat(item.readcount || 0)} 阅读</span>,
                                <Space key="list-vertical-like-o" onClick={() => likeArticle(item.id)}>
                                    {item.isLike ? <LikeTwoTone twoToneColor="#eb2f96"/> : <LikeOutlined/>}
                                    {countFormat(item.likecount || 0)}
                                </Space>,
                                <Space key="list-vertical-star-o" onClick={() => collectArticle(item.id, item.title, item.desc)}>
                                    {item.isCollect ? <StarTwoTone/> : <StarOutlined/>}
                                </Space>
                            ]}
                            extra={
                                <div className="article-cover">
                                    <img
                                        className="article-cover-img"
                                        alt="logo"
                                        src={`https://qny.amojito.cn/cover${index % 5}.jpg`}
                                    />
                                </div>
                            }
                        >
                            <Skeleton loading={showSkeleton} active>
                                <List.Item.Meta
                                    title={
                                        <div className="article-title-c" onClick={() => history.push('/article/detail/' + item.id)}>
                                            {
                                                item.istop === '1' ? 
                                                <Tag color="#108ee9">置顶</Tag>
                                                : ''
                                            }
                                            <div className="article-title">{item.title}</div>
                                        </div>
                                    }
                                    description={
                                        <div className="article-desc">
                                            简要描述：{item.desc}
                                        </div>
                                    }
                                />
                            </Skeleton>
                        </List.Item>
                    )}
                />
            </div>

            <Modal
                visible={appreciateVisible}
                title="微信赞赏码"
                footer={null}
                width="360px"
                onCancel={() => setAppreciateVisible(false)}
            >
                <PhotoProvider>
                    <PhotoConsumer src={require("../../../assets/img/zanshang.jpg")} intro={'支持一下'}>
                        <img src={require("../../../assets/img/zanshang.jpg")} style={{width: '100%'}} alt=""/>
                    </PhotoConsumer>
                </PhotoProvider>
            </Modal>
        </Container>
    )
}

const mapState = (state) => ({
    keyword: state.keyword,
    homeArticleList: state.homeArticleList,
    homeTopDis: state.homeTopDis
})

const mapDispatch = (dispatch) => ({
    changeHomeArticleList(data){
		dispatch(changeHomeArticleList(data))
    },
    changeHomeTopDis(data){
        dispatch(changeHomeTopDis(data))
    }
})

export default connect(mapState, mapDispatch)(Home)